﻿using System;

namespace ToyundaPhone.FileFormat
{
	public class FixedTextColumnCountFilter : IRowGenerator
	{
		private IRowGenerator source;
		private int columnCount;
		private string concatText;

		public FixedTextColumnCountFilter(IRowGenerator source, int columnCount, string concatText)
		{
			this.source = source;
			this.columnCount = columnCount;
			this.concatText = concatText;
		}

		#region IRowGenerator Members

		public object[] GetNextRow()
		{
			object[] row = source.GetNextRow();
			if (row != null)
			{
				object[] newRow = new object[columnCount];
				int i = 0;
				int limit = Math.Min(newRow.Length, row.Length);
				while (i < limit)
				{
					newRow[i] = row[i];
					i++;
				}
				if ((row.Length > columnCount) && (newRow[newRow.Length - 1] is string))
				{
					while (i < row.Length)
					{
						if (row[i] is string)
						{
							newRow[newRow.Length - 1] = (string)newRow[newRow.Length - 1] + concatText + (string)row[i];
						}
						i++;
					}
				}
				row = newRow;
			}
			return row;
		}

		#endregion
	}
}
